<template>
  <div>
    <div id="container"></div>
    <el-dialog :visible.sync="visible" :title="title"></el-dialog>
    <el-form ref="form" :model="form">
      <el-form-item prop="dateRange" :rules="[{required: true, message: '请选择时间范围'}]">
        <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <el-button @click="search">查询</el-button>
  </div>
</template>

<script>
import {Timeline} from 'vis-timeline'
import {DataSet} from 'vis-data'
import moment from 'moment'

export default {
  data() {
    return {
      visible: false,
      title: '',
      form: {
        dateRange: []
      },
      timeline: undefined
    }
  },
  methods: {
    search() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.dateRange = [moment(this.form.dateRange[0]).format('YYYY-MM-DD'), moment(this.form.dateRange[1]).format('YYYY-MM-DD')]
          this.timeline.setWindow(this.form.dateRange[0], this.form.dateRange[1]);
        }
      })
    },
    renderTimeLine() {
      const container = document.getElementById('container')
      const items = new DataSet([
        {id: 1, content: 'item 1', start: '2014-04-20'},
        {id: 2, content: 'item 2', start: '2014-04-14'},
        {id: 3, content: 'item 3', start: '2014-04-18'},
        {id: 4, content: 'item 4', start: '2014-04-16', end: '2014-04-19'},
        {id: 5, content: 'item 5', start: '2014-04-25'},
        {id: 6, content: 'item 6', start: '2014-04-27'},
        {id: 7, content: 'item 33', start: '2014-04-20'},
        {id: 8, content: 'item 44', start: '2014-04-20'},
      ])
      const options = {
        max: moment().add(1, 'days').format('YYYY-MM-DD'),
        minHeight: 300,
        maxHeight: 400,
      }

      // Create a Timeline
      this.timeline = new Timeline(container, items, options);

      this.timeline.on('click', (e) => {
        if (e.what === 'item') {
          this.visible = true
          this.title = e.item + ''
        }
      });
    }
  },
  mounted() {
    this.renderTimeLine()
  }
}
</script>

<style scoped>
#container {
  width: 800px;
  height: 400px;
}
</style>
